package com.yuexunit.mobilenurse.module.Patients.ui;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

import com.imscs.barcodemanager.BarcodeManager;
import com.imscs.barcodemanager.BarcodeManager.ScanResult;
import com.imscs.barcodemanager.Constants;
import com.yuexunit.mobilenurse.R;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.PatientDetail.ui.Act_PatientDetail_M80;
import com.yuexunit.mobilenurse.module.Patients.ui.fragment.Frag_PatientList_M80;
import com.yuexunit.mobilenurse.module.Patients.ui.fragment.Frag_Upload;

import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.ui.KJFragment;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.io.IOException;

/**
 * Created by work-jx on 2016/8/18.
 */
public class Act_Main_M80 extends KJActivity implements BarcodeManager.OnEngineStatus {
    @BindView(id = R.id.bottombar_content1, click = true)
    private RadioButton mRbtnContent1;
    @BindView(id = R.id.bottombar_content2, click = true)
    private RadioButton mRbtnContent2;
    @BindView(id = R.id.bottombar_content3, click = true)
    private RadioButton mRbtnContent3;

    private Frag_PatientList_M80 contentFragment1;
    private Frag_Upload contentFragment2;
    private Frag_Upload contentFragment3;
    private KJFragment currentFragment;

    //扫描
    private DoDecodeThread mDoDecodeThread;
    private BarcodeManager mBarcodeManager = null;
    private final int SCANKEY_LEFT = 301;
    private final int SCANKEY_RIGHT = 300;
    private final int SCANKEY_CENTER = 302;
    private final int SCANTIMEOUT = 3000;
    private Handler mDoDecodeHandler;
    private boolean mbKeyDown = true;
    class DoDecodeThread extends Thread {
        public void run() {
            Looper.prepare();
            mDoDecodeHandler = new Handler();
            Looper.loop();
        }
    }

    @Override
    public void initData() {
        super.initData();
        AppConfig.ISOVER_PATIENT=false;
        contentFragment1 = new Frag_PatientList_M80();
//        contentFragment2 = new Frag_Upload();
        contentFragment3 = new Frag_Upload();
    }

    @Override
    public void initWidget() {
        super.initWidget();
        changeFragment(contentFragment1);

        mDoDecodeThread = new DoDecodeThread();
        mDoDecodeThread.start();
    }

    @Override
    public void onResume(){
        super.onResume();
        if (mBarcodeManager == null) {
            // initialize decodemanager
            mBarcodeManager = new BarcodeManager(this, this);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(mBarcodeManager != null) {
            try {
                mBarcodeManager.release();
                mBarcodeManager = null;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onStop() {
        super.onStop();

    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        if (mBarcodeManager != null) {
            try {

                mBarcodeManager.release();
                mBarcodeManager = null;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    private void doScanInBackground() {
        mDoDecodeHandler.post(new Runnable() {

            @Override
            public void run() {
                if (mBarcodeManager != null) {
                    // TODO Auto-generated method stub
                    try {
                        synchronized (mBarcodeManager) {
                            mBarcodeManager.executeScan(SCANTIMEOUT);
                        }

                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {
            case KeyEvent.KEYCODE_ENTER:
            case SCANKEY_LEFT:
            case SCANKEY_CENTER:
            case SCANKEY_RIGHT:
            case KeyEvent.KEYCODE_SLASH: // hal key
                try {
                    if (mbKeyDown) {
                        DoScan();
                        mbKeyDown = false;
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return true;
            case KeyEvent.KEYCODE_BACK:
                this.finish();
                return true;
            default:
                return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_ENTER:
            case SCANKEY_LEFT:
            case SCANKEY_CENTER:
            case SCANKEY_RIGHT:
            case KeyEvent.KEYCODE_SLASH: // hal key
                try {
                    mbKeyDown = true;
                    cancleScan();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return true;
            case KeyEvent.KEYCODE_BACK:
                this.finish();
                return true;
            default:
                return super.onKeyUp(keyCode, event);
        }
    }

    @Override
    public void setRootView() {
        setContentView(R.layout.act_main);
    }

    @Override
    public void widgetClick(View v) {
        super.widgetClick(v);
        switch (v.getId()) {
            case R.id.bottombar_content1:
                changeFragment(contentFragment1);
                break;
            case R.id.bottombar_content2:
                //changeFragment(contentFragment2);
                break;
            case R.id.bottombar_content3:
                changeFragment(contentFragment3);
                break;
            default:
                break;
        }
    }

    public void changeFragment(KJFragment targetFragment) {
        currentFragment = targetFragment;
        super.changeFragment(R.id.main_content, targetFragment);
    }

    /**
     * 通过dispatchTouchEvent每次ACTION_DOWN事件中动态判断非EditText本身区域的点击事件，然后在事件中进行屏蔽。然后当点击不是EditText时候，进行隐藏键盘操作
     *
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {

        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件\
                return false;
            } else {
                return true;
            }
        }
        return false;
    }


    private void DoScan() throws Exception {
        doScanInBackground();
    }

    private void cancleScan() throws Exception {
        if (mBarcodeManager != null) {
            mBarcodeManager.exitScan();
        }
    }

    @Override
    public void onEngineReady() {
        // TODO Auto-generated method stub
        ScanResultHandler.sendEmptyMessage(Constants.DecoderReturnCode.RESULT_DECODER_READY);
    }

    @Override
    public int scanResult(boolean suc,BarcodeManager.ScanResult result) {
        // TODO Auto-generated method stub
        Message m = new Message();
        m.obj = result;
        if (suc){
            // docode successfully
            m.what = Constants.DecoderReturnCode.RESULT_SCAN_SUCCESS;
        }else{
            m.what = Constants.DecoderReturnCode.RESULT_SCAN_FAIL;

        }
        ScanResultHandler.sendMessage(m);
        return 0;
    }

    private Handler ScanResultHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constants.DecoderReturnCode.RESULT_SCAN_SUCCESS:
                    String strDecodeResult = "";
                    ScanResult decodeResult = (ScanResult) msg.obj;

                    String result = decodeResult.result;
                    if (mBarcodeManager != null) {
                        mBarcodeManager.beepScanSuccess();
                    }
                    if(!result.equals(""))
                    {
                        if(AppConfig.ISOVER_PATIENT) {
                            if (result.length() == Integer.valueOf(PreferenceHelper.readString(aty, AppConfig.JCI_INFO, AppConfig.JCI_WD_RULE))) {
                                if(contentFragment1.JudgeVisitNo(result)) {
                                    PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO, result);
                                    AppConfig.VISITNO = result;
                                    showActivity(aty, Act_PatientDetail_M80.class);
                                }
                                else {
                                    Toast.makeText(aty, "非本病区病人!", Toast.LENGTH_LONG).show();
                                }
                            } else {
                                Toast.makeText(aty, "请扫描病人腕带!", Toast.LENGTH_LONG).show();
                            }
                        }
                        else{
                            Toast.makeText(aty, "病人列表尚未加载完!请加载完毕后,再扫描!", Toast.LENGTH_LONG).show();
                        }
                    }
                    break;

                case Constants.DecoderReturnCode.RESULT_SCAN_FAIL: {
                    if (mBarcodeManager != null) {
                        mBarcodeManager.beepScanFail();
                    }
                }
                break;
                case Constants.DecoderReturnCode.RESULT_DECODER_READY: {
                }
                break;
                default:
                    super.handleMessage(msg);
                    break;
            }
        }
    };
}
